<!-- Vue组件 -->
<template>
  <div class="cesiumContainerBox">
    <div id="cesiumContainer" style="width: 100%; height: 91vh"></div>
  </div>
</template>

<script>
export default {
  name: "CesiumSiteViewer",
  props: {
    cesiumData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      viewer: null,
      entities: [],
    };
  },
  watch: {
    cesiumData: {
      deep: true,
      handler(newData) {
        this.updateEntities(newData);
      },
    },
  },
  mounted() {
    this.initCesiumContainer();
    // 初始数据绘制
    if (this.cesiumData && this.cesiumData.length > 0) {
      this.updateEntities(this.cesiumData);
    }
  },
  methods: {
    //初始化cesium
    initCesiumContainer() {
      this.viewer = new Cesium.Viewer("cesiumContainer", {
        baseLayerPicker: false,
        imageryProvider: false,
        sceneMode: Cesium.SceneMode.SCENE2D,
        animation: false,
        geocoder: false,
        homeButton: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        timeline: false,
        infoBox: false,
        fullscreenButton: true,
      });
      // 获取默认的必应底图并移除（如果存在）
      const defaultLayer = this.viewer.imageryLayers.get(0);
      if (defaultLayer) {
        this.viewer.imageryLayers.remove(defaultLayer);
      }

      //瓦片图中心显示
      var centerLongitude = 131;
      var centerLatitude = 40.81;
      var halfSize = 0.05;

      // 创建限定显示范围的矩形区域
      var rectangle = Cesium.Rectangle.fromDegrees(
        centerLongitude - halfSize,
        centerLatitude - halfSize,
        centerLongitude + halfSize,
        centerLatitude + halfSize
      );

      // 禁用用户平移操作
      this.viewer.scene.screenSpaceCameraController.enableTranslate = true;
      // 设置初始视图到矩形中心
      var initialPosition = Cesium.Rectangle.center(rectangle);
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromRadians(
          initialPosition.longitude,
          initialPosition.latitude,
          500000
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0),
          pitch: Cesium.Math.toRadians(-90),
          roll: 0,
        },
      });
      // 可选：进一步限制交互
      this.viewer.scene.screenSpaceCameraController.enableRotate = false;
      this.viewer.scene.screenSpaceCameraController.enableTilt = false;

      // 加载本地瓦片（需提前配置离线数据源）
      const offlineProvider = new Cesium.UrlTemplateImageryProvider({
        url: "/gismap/{z}/{y}/{x}.png",
        minimumLevel: 0,
        maximumLevel: 8,
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
      });
      this.viewer.imageryLayers.addImageryProvider(offlineProvider);

      this.viewer.scene.screenSpaceCameraController.minimumZoomDistance = 10000;
      this.viewer.scene.screenSpaceCameraController.maximumZoomDistance = 10000000;
    },
    // 更新实体点
    updateEntities(data) {
      // 清除现有实体
      this.clearEntities();

      // 创建新实体
      data.forEach(item => {
        if (item.longitude && item.latitude) {
          const entity = this.viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(
              item.longitude,
              item.latitude
            ),
            point: {
              pixelSize: 8,
              color: Cesium.Color.RED,
              outlineColor: Cesium.Color.WHITE,
              outlineWidth: 2,
            },
            label: {
              text: `经度: ${item.longitude.toFixed(6)}, 纬度: ${item.latitude.toFixed(6)}`,
              font: "14px sans-serif",
              fillColor: Cesium.Color.YELLOW,
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              pixelOffset: new Cesium.Cartesian2(0, -15),
              showBackground: true,
              backgroundColor: new Cesium.Color(0.1, 0.1, 0.1, 0.7),
              padding: 5,
            },
          });
          this.entities.push(entity);
        }
      });
    },

// 清除所有实体
clearEntities() {
  // 正确实现：遍历并移除所有实体
  this.entities.forEach(entity => {
    this.viewer.entities.remove(entity);
  });
  
  // 清空实体数组
  this.entities = [];
},
  },
  beforeDestroy() {
    if (this.viewer) {
      this.viewer.destroy();
    }
  },
};
</script>

<style lang="less" scoped>
/* 移除冗余样式 */
.cesiumContainerBox {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/* 全局样式 */
::v-deep .cesium-credit-textContainer,
::v-deep .cesium-credit-logoContainer,
::v-deep .cesium-credit-expand-link {
  display: none !important;
}
</style>
